﻿using LuShanTea.Admin.Web.App_Start;
using LuShanTea.Admin.Web.Models;
using LuShanTea.DTO;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class OrderController : Controller
    {
        public IOrderService OrderService { get; set; }

        public IAreaService AreaService { get; set; }

        public ICityService CityService { get; set; }

        public IIdNameService IdNameService { get; set; }

        public IProvinceService ProvinceService { get; set; }

        public IAddressService AddressService { get; set; }

        private const string ORDERINFO = "OrderInfo";

        [CheckPermission("Order.List")]
        // GET: Order
        public ActionResult List()
        {
            ViewBag.TotalCount = OrderService.GetTotalCount();

            return View();
        }

        [CheckPermission("Order.List")]
        [HttpPost]
        public ActionResult List(int currentPage)
        {
            //TODO:性能优化
            int pageSize = 10;

            var orders = OrderService.GetPageDataOrder(pageSize, currentPage);

            int length = orders.Length;

            if (length <= 0)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "没有数据" });
            }

            return Json(new AjaxResult { Status = "ok", Data = orders });
        }

        [CheckPermission("Order.Edit")]
        public ActionResult Edit(long id)
        {
            var order = OrderService.GetById(id);

            if (order == null)
            {
                return Content("未找到ID为" + id + "的订单");
            }



            //省市区
            long areaId = 1;
            if (order.ReciverAddress != null)
            {
                areaId = order.AreaId;
            }

            var area = AreaService.GetById(areaId);
            var cityId = area.CityId;
            var city = CityService.GetById(cityId);
            var provinceId = ProvinceService.GetById(city.ProId).Id;
            var province = ProvinceService.GetById(provinceId);

            var statues = IdNameService.GetNameByTypeName("订单状态");
            var payWays = IdNameService.GetNameByTypeName("付款方式");
            var receipts = IdNameService.GetNameByTypeName("发票类型");
            var express = IdNameService.GetNameByTypeName("快递公司");

            var provinces = ProvinceService.GetAll();

            OrderGetModel orderGetModel = new OrderGetModel()
            {
                Order = order,
                Statues = statues,
                Express = express,
                PayWays = payWays,
                Provinces = provinces,
                Receipts = receipts,
                ProvinceId = provinceId,
                CityId = cityId,
                AreaId = order.AreaId
            };

            return View(orderGetModel);
        }

        [CheckPermission("Order.Edit")]
        [HttpPost]
        public ActionResult Edit(OrderDTO orderDTO)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }

            var order = OrderService.GetById(orderDTO.Id);
            var area = AreaService.GetById(orderDTO.AreaId);
            var expres = IdNameService.GetById(orderDTO.ExpressId);
            var statue = IdNameService.GetById(orderDTO.StatusId);
            var payWay = IdNameService.GetById(orderDTO.PayWayId);
            var receipt = IdNameService.GetById(orderDTO.ReceiptId);

            bool isChecked = order == null || area == null || expres == null || statue == null || payWay == null || receipt == null;

            if (isChecked)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "表单数据不完整" });
            }

            AddressAddNewDTO addresUpdateDTO = new AddressAddNewDTO()
            {
                Id = (long)order.AddressId,
                CreateDateTime = orderDTO.CreateDateTime,
                AreaId = orderDTO.AreaId,
                ReciverAddress = orderDTO.ReciverAddress,
                PhoneNum = orderDTO.PhoneNum,
                PostEmail = orderDTO.PostEmail,
                ReciverName = orderDTO.ReciverName,
                UserId = order.UserId
            };

            long addressId = AddressService.UpdateAddres(addresUpdateDTO);

            order.Amount = orderDTO.Amount;
            order.ExpressId = orderDTO.ExpressId;
            order.LeaveWord = orderDTO.LeaveWord;
            order.PayWayId = orderDTO.PayWayId;
            order.ReceiptId = orderDTO.ReceiptId;
            order.StatusId = orderDTO.StatusId;
            order.AddressId = addressId;

            OrderService.UpdateOrder(order);
            return Json(new AjaxResult { Status = "ok" });
        }



        /// <summary>
        /// 获取省份下所有的市
        /// </summary>
        /// <param name="provinceId"></param>
        /// <returns></returns>
        [HttpPost]
        [CheckPermission("City.List")]
        public ActionResult GetCity(long provinceId)
        {
            var province = ProvinceService.GetById(provinceId);

            if (province == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "省份未找到" });
            }

            var cities = CityService.GetByProvId(provinceId);

            return Json(new AjaxResult { Status = "ok", Data = cities });

        }

        [HttpPost]
        [CheckPermission("Area.List")]
        public ActionResult GetArea(long cityId)
        {
            var city = CityService.GetById(cityId);

            if (city == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "省份未找到" });
            }

            var cities = AreaService.GetByCityId(cityId);

            return Json(new AjaxResult { Status = "ok", Data = cities });

        }

        [CheckPermission("Order.Delete")]
        [HttpPost]
        public ActionResult Delete(long orderId)
        {
            OrderService.MarkDeleted(orderId);

            return Json(new AjaxResult { Status = "ok" });
        }

        [CheckPermission("Order.Delete")]
        [HttpPost]
        public ActionResult BatchDel(long[] orderIds)
        {
            foreach (var orderId in orderIds)
            {
                OrderService.MarkDeleted(orderId);
            }

            return Json(new AjaxResult { Status = "ok" });
        }
    }
}